<template>
  <a-modal
    title="新增绩效规则"
    :width="1600"
    :visible="visible"
    :confirmLoading="false"
    :closable="false"
    :cancelButtonProps="{ style: { visibility: 'hidden' }}"
    @ok="() => { $emit('ok') }"
    @cancel="() => { $emit('cancel') }">
    <a-spin :spinning="false">
      <div style="display: flex;width: 1600px ;gap: 12px">
        <a-menu
          style="width: 220px"
          mode="inline"
          :openKeys="openKeys"
          :selectedKeys="selectedKeys">
          <a-sub-menu
            v-for="subMenu in menu"
            :key="subMenu.key"
            @titleClick="titleClick">
            <template #title>
              {{ subMenu.title }}
            </template>
            <a-menu-item
              @click="itemClick"
              v-for="menuItem in subMenu.children"
              :key="menuItem.key">
              {{ menuItem.title }}
              <img
                v-if="saveList.find(item => item.key === menuItem.key)"
                style="width: 15px"
                src="~@/assets/icons/done.svg" />
            </a-menu-item>
          </a-sub-menu>
        </a-menu>
        <div style="width: 1400px;">
          <div>
            <a-row>
              <a-col :md="14">
                <h3>当前年份：{{ year }} 当前版本：{{ version }}
                  毛利去除率：
                  <a-input-number
                    v-show="rateEdit"
                    style="margin-right: 20px;margin-left: 20px;width: 200px"
                    placeholder="请输入毛利率(%)"
                    v-model="marginRemovalRate" />
                  <a-button
                    v-show="rateEdit"
                    @click="() => { this.rateEdit = false }"
                    type="primary">提交</a-button>
                  <span v-show="!rateEdit">{{ marginRemovalRate }}%</span>
                </h3>
              </a-col>
              <a-col
                :offset="2"
                :md="8">
                <div style="float: right; margin: 0 60px 20px 0;">
                  <a-button
                    @click="handleEdit"
                    v-if="!isEdit"
                    style="margin-right: 10px">编辑</a-button>
                  <a-button
                    @click="() => { this.isEdit = false }"
                    v-if="isEdit"
                    style="margin-right: 10px">取消</a-button>
                  <a-button
                    type="primary"
                    @click="handleSubmit">保存</a-button>
                </div>
              </a-col>
            </a-row>

          </div>
          <yewu-cards
            :isEdit="isEdit"
            :yewuConfig="yewuConfig"
            :demo="false"
            :job2="selectedKeys[0]"
            ref="yewu"
            v-if="job1 === 1" />
          <engine-cards
            :isEdit="isEdit"
            ref="engine"
            :engineConfig="engineConfig"
            :demo="false"
            v-if="job1 === 2" />
          <prod-cards
            :isEdit="isEdit"
            ref="prod"
            :prodConfig="prodConfig"
            :demo="false"
            v-if="job1 === 3" />
          <admin-cards
            :isEdit="isEdit"
            ref="admin"
            :adminConfig="adminConfig"
            :demo="false"
            v-if="job1 === 4" />
        </div>
      </div>
    </a-spin>
  </a-modal>
</template>

<script>
import { menu, yewuConfig, engineConfig, prodConfig, adminConfig } from './config'
import YewuCards from '../tables/YewuCards'
import EngineCards from '../tables/EngineCards'
import ProdCards from '../tables/ProdCards'
import AdminCards from '../tables/AdminCards'
import { yewuToTable, tableToYewu, enginerToTable, tableToEnginer, prodToTable, tableToProd } from '../tables/config'
import {
  savePerformanceConfigInfo,
  getPerformanceConfigInfo,
  updatePerformanceConfigInfo
} from '@/api/performanceConfig'
import _ from 'lodash'

export default {
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    year: {
      type: [Number, String],
      default: () => undefined
    },
    version: {
      type: [Number, String],
      default: () => undefined
    }
  },
  components: {
    YewuCards,
    EngineCards,
    ProdCards,
    AdminCards
  },
  data () {
    this.desc = ''
    this.menu = menu
    this.yewuConfig = yewuConfig
    this.engineConfig = engineConfig
    this.prodConfig = prodConfig
    this.adminConfig = adminConfig
    return {
      isEdit: false,
      openKeys: [1],
      selectedKeys: [1],
      job1: 1,
      saveList: [],
      performanceConfigId: undefined,
      marginRemovalRate: undefined,
      performanceConfigIds: undefined,
      rateEdit: true
    }
  },
  created () {},
  watch: {
    visible: function (visible) {
      this.rateEdit = true
      this.saveList = []
      this.openKeys = [1]
      this.selectedKeys = [1]
      this.marginRemovalRate = undefined
    },
    selectedKeys: function (now, old) {
        now[0] !== old[0] && this.getCurPerform()
    }
  },

  methods: {
    getCurPerform (param) {
      getPerformanceConfigInfo({
        year: this.year,
        version: this.version,
        job1: this.job1,
        job2: this.selectedKeys[0] === 'sc' ? null : this.selectedKeys[0],
        ...param
      }).then(res => {
        this.performanceConfigId = _.get(res, ['data', 'performanceConfigId']) ? res.data.performanceConfigId : undefined
        this.performanceConfigIds = _.get(res, ['data', 'performanceConfigIds']) ? res.data.performanceConfigIds : undefined
        if (this.performanceConfigId || this.performanceConfigIds) {
        switch (this.job1) {
          case 1:
            this.yewuConfig = tableToYewu(res.data)
            break
          case 2:
            this.engineConfig = tableToEnginer(res.data)
            break
          case 3:
            this.prodConfig = tableToProd(res.data)
            break
          case 4:
            const { ext1 } = res.data || {}
            this.adminConfig = { rate: ext1 }
            break
        }
        } else {
          this.yewuConfig = yewuConfig
          this.engineConfig = engineConfig
          this.prodConfig = prodConfig
          this.adminConfig = adminConfig
        }
        // 数据更新后 页面不更新，通过改变job1触发v-if 重新渲染
        const temp = this.job1
        this.job1 = '100'
        this.$nextTick(() => {
          this.job1 = temp
        })
      })
    },
    updateInfo (param) {
      if (this.performanceConfigId || this.performanceConfigIds) {
        return updatePerformanceConfigInfo({
          performanceConfigId: this.performanceConfigId,
          performanceConfigIds: this.performanceConfigIds,
          job1: this.performanceConfigIds ? 3 : null,
          ...param
        })
      } else {
        return savePerformanceConfigInfo({
          year: this.year,
          version: this.version,
          job1: this.job1,
          job2: this.selectedKeys[0],
           marginRemovalRate: (this.marginRemovalRate / 100).toFixed(6),
          ...param
        })
      }
    },
    handleChange (val) {},
    // menu 方法，收起展开等
    titleClick (e) {
      const _key = e.key
      this.job1 = e.key
      if (this.openKeys.includes(_key)) {
        this.openKeys = this.openKeys.filter(k => k !== _key)
      } else {
        this.openKeys.push(_key)
      }
      const subKey = this.menu.find(item => item.key === _key).children[0].key
      this.selectedKeys = [subKey]
    },
    itemClick (e) {
      this.selectedKeys = [e.key]
      this.job1 = this.menu.find(item => item.children.map(i => i.key).includes(e.key)).key
      this.getCurPerform()
    },
    // 将新增的已保存的规则更新
    addDatatoList (data) {
      const key = this.selectedKeys[0]
      let preData = this.saveList?.find(item => item.key === key)
      if (preData) {
        preData = { key, data }
      } else {
        this.saveList.push({ key, data })
      }
    },
    handleEdit () {
      if (this.rateEdit) {
        this.$message.error('先输入该版本的毛利去除率')
      } else {
        this.isEdit = true
      }
    },
    handleSubmit () {
      switch (this.job1) {
        case 1:
          const yewuConfig = this.$refs.yewu.getConfig()
          let param = yewuToTable(yewuConfig, this.selectedKeys[0] === 2)
          if (!param) {
            this.$message.error('请正确填写参数')
            return
          }
          this.updateInfo(param).then(() => {
            this.getCurPerform()
            this.addDatatoList(yewuConfig)
            this.yewuConfig = yewuConfig
          })
          break
        case 2:
          const engineConfig = this.$refs.engine.getConfig()
          param = enginerToTable(engineConfig)
          if (!param) {
            this.$message.error('请正确填写参数')
            return
          }
          this.updateInfo(param).then(() => {
            this.getCurPerform()
            this.addDatatoList(engineConfig)
          this.engineConfig = engineConfig
          })
          break
        case 3:
          const prodConfig = this.$refs.prod.getConfig()
          param = prodToTable(prodConfig)
          if (!param) {
            this.$message.error('请正确填写参数')
            return
          }
          this.updateInfo(param).then(() => {
            this.getCurPerform()
            this.addDatatoList(prodConfig)
          this.prodConfig = prodConfig
          })
          break
        case 4:
          const adminConfig = this.$refs.admin.getConfig()
          if (!adminConfig['rate']) {
            this.$message.error('请正确填写参数')
            return
          }
          this.updateInfo({ ext1: adminConfig.rate }).then(() => {
            this.getCurPerform()
            this.addDatatoList(prodConfig)
            this.adminConfig = adminConfig
          })
          break
      }
      this.isEdit = false
    }
  }
}
</script>
<style lang="less" scoped>
/deep/.ant-input-number {
  width: fit-content;
}
</style>
